<?php

namespace app\api\controller;

use app\common\controller\ApiBase;
use app\Constant\ApiConstant;
use app\model\AgentDistribution;
use app\model\AgentGoods;
use app\model\AgentMini;
use app\model\DistributionSetting;
use app\model\GoodsCategory;
use app\model\GoodsCollection;
use app\model\GoodsColumn;
use app\model\GoodsColumnGoods;
use app\model\GoodsFree;
use app\model\GoodsType;
use app\model\Shop;
use app\model\ShopCategory;
use app\model\UserOauth;
use app\service\DeepSeekService;
use Exception;
use think\facade\Request;
use think\response\Json;
use Wechat\CommerceApp;

class Goods extends ApiBase
{
	/**
	 * 分类列表
	 *
	 * @return Json
	 */
	public function category()
	{
		$lists = GoodsCategory::field('id, name, type')
			->where('status', 1)
			->order('sort asc, id asc')
			->select();
		return $this->callback(ApiConstant::SUCCESS, 'success', $lists);
	}

	/**
	 * 专区列表
	 *
	 * @return Json
	 */
	public function type()
	{
		$lists = GoodsType::field('id, name, type')
			->where('status', 1)
			->order('sort asc, id asc')
			->select();
		return $this->callback(ApiConstant::SUCCESS, 'success', $lists);
	}

	/**
	 * 商品列表
	 *
	 * @return Json
	 */
	public function list()
	{
		$page       = Request::get('page') ?: 1;
		$page_size  = Request::get('page_size') ?: 10;
		$category   = Request::get('category') ?: 0;
		$type       = Request::get('type') ?: 0;
		$keyword    = Request::get('keyword');
		$shop_appid = Request::get('shop_appid');
		$sort_field = Request::get('sort_field') ?: '';
		$sort_type  = Request::get('sort_type') ?: '';

		$user  = \app\model\User::field('id, level, agent_id')->where('token', $this->token)->find();
		$level = $user['level'] ?? 1;
		$query = \app\model\Goods::field('id, product_id, shop_appid, head_supplier_appid, title, product_promotion_link, image, sale_price, flags, share_commission, subsidy_commission, commission')
			->where('status', 1);
		if (!empty($category)) {
			$query->where('category_id', $category);
		}
		if (!empty($type)) {
			$query->where('type', $type);
		}
		if (!empty($shop_appid)) {
			$query->where('shop_appid', $shop_appid);
		}
		if (!empty($keyword)) {
			$query->where('title', 'like', "%{$keyword}%");
		}
		if (!empty($user['agent_id'])) {
			$goods_type = AgentMini::where('agent_id', $user['agent_id'])->value('goods_type');
			//合作商自定义商品
			if ($goods_type == 2) {
				$goods_ids = AgentGoods::where('agent_id', $user['agent_id'])->column('goods_id');
				$query->whereIn('id', $goods_ids);
			}
		}

		$total = $query->count();

		$order = 'sort asc, update_time desc';
		if ($sort_field && $sort_type) {
			$order = $sort_field . ' ' . $sort_type . ', sort asc';
		}

		$lists = $query
			->withAttr('sale_price', function ($value) {
				return $value > 0 ? number_format($value / 100, 2) : 0;
			})
			->withAttr('share_commission', function ($value, $data) use ($level, $user) {
				//如果用户分销等级是2级，则重新计算佣金
				if ($level >= 2 || !empty($user['agent_id'])) {
					$setting = AgentDistribution::getLevelInfo($user['agent_id'], $level, 1);
					$ratio   = $setting['ratio'] / 100;
					$price   = round($data['commission'] * $ratio);
				} else {
					$price = $value;
				}
				$price = $price + $data['subsidy_commission'];
				return $price > 0 ? number_format($price / 100, 2) : 0;
			})
			->withAttr('flags', function ($value) {
				return $value ? explode(',', $value) : [];
			})
			->page($page, $page_size)
			->order($order)
			->select();

		$res = [
			'total' => $total,
			'list'  => $lists,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	public function info()
	{
		$id   = Request::get('id');
		$user = \app\model\User::field('id, level, agent_id')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '用户未登录');
		}
		$level = $user['level'] ?? 1;

		$info = \app\model\Goods::field('id, product_id, shop_appid, head_supplier_appid, title, product_promotion_link, image, sale_price, flags, share_commission, head_imgs, subsidy_commission, commission, share_text')
			->where('status', 1)
			->where('id', $id)
			->with(['shop'])
			->withAttr('sale_price', function ($value) {
				return $value > 0 ? number_format($value / 100, 2) : 0;
			})
			->withAttr('share_commission', function ($value, $data) use ($level, $user) {
				//如果用户分销等级是2级，则重新计算佣金
				if ($level == 2 || !empty($user['agent_id'])) {
					$setting = AgentDistribution::getLevelInfo($user['agent_id'], $level, 1);
					$ratio   = $setting['ratio'] / 100;
					$price   = round($data['commission'] * $ratio);
				} else {
					$price = $value;
				}
				$price = $price + $data['subsidy_commission'];
				return $price > 0 ? number_format($price / 100, 2) : 0;
			})
			->withAttr('flags', function ($value) {
				return $value ? explode(',', $value) : [];
			})
			->withAttr('head_imgs', function ($value) {
				return $value ? json_decode($value, true) : [];
			})
			->find();
		if (!$info) {
			\app\model\Goods::where('id', $id)->update(['status' => 5]);
			return $this->callback(ApiConstant::PARAM_ERROR, '商品不存在');
		}

		// 升级V3可得佣金金额
		$setting              = AgentDistribution::getLevelInfo($user['agent_id'], 3, 1);
		$ratio                = $setting['ratio'] / 100;
		$v3Commission         = round($info['commission'] * $ratio) + $info['subsidy_commission'];
		$info['v3Commission'] = number_format($v3Commission / 100, 2);

		//是否收藏
		$collection            = GoodsCollection::where('user_id', $user['id'])
			->where('goods_id', $id)
			->where('status', 1)
			->value('id');
		$info['is_collection'] = $collection ? 1 : 0;

		$openid = UserOauth::where('user_id', $user['id'])->value('openid');
		try {
			$res = CommerceApp::getInstance()->getProductPromotionLink($info['product_id'], $info['shop_appid'], $info['head_supplier_appid'], $openid);
			if ($res) {
				$info['product_promotion_link'] = $res;
			}
		} catch (Exception $e) {
		}

		return $this->callback(ApiConstant::SUCCESS, 'success', $info);
	}

	/**
	 * 商品收藏列表
	 *
	 * @return Json
	 */
	public function collection()
	{
		$page      = Request::get('page') ?: 1;
		$page_size = Request::get('page_size') ?: 10;
		$keyword   = Request::get('keyword');
		$field     = Request::get('field') ?: '';
		$order     = Request::get('order') ?: 'desc';

		$user = \app\model\User::field('id, level, agent_id')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '用户未登录');
		}
		$user_id = $user['id'];
		$level   = $user['level'] ?? 1;
		$query   = GoodsCollection::field('c.id, c.goods_id, g.title, g.image, g.sale_price, g.share_commission, g.subsidy_commission, g.commission')
			->alias('c')
			->leftJoin('goods g', 'g.id = c.goods_id')
			->where('c.status', 1)
			->where('c.user_id', $user_id);
		if ($keyword) {
			$query->where('g.title', 'like', "%{$keyword}%");
		}
//        if ($user['agent_id']) {
//            $goods_type = AgentMini::where('agent_id', $user['agent_id'])->value('goods_type');
//            //合作商自定义商品
//            if ($goods_type == 2) {
//                $goods_ids = AgentGoods::where('agent_id', $user['agent_id'])->column('goods_id');
//                $query->whereIn('goods_id', $goods_ids);
//            }
//        }
		$total = $query->count();

		if ($field) {
			$query->order("g.$field", $order);
		}
		$lists = $query
			->withAttr('sale_price', function ($value) {
				return $value > 0 ? number_format($value / 100, 2) : 0;
			})
			->withAttr('share_commission', function ($value, $data) use ($level, $user) {
				//如果用户分销等级是2级，则重新计算佣金
				if ($level == 2 || !empty($user['agent_id'])) {
					$setting = AgentDistribution::getLevelInfo($user['agent_id'], $level, 1);
					$ratio   = $setting['ratio'] / 100;
					$price   = round($data['commission'] * $ratio);
				} else {
					$price = $value;
				}
				$price = $price + $data['subsidy_commission'];
				return $price > 0 ? number_format($price / 100, 2) : 0;
			})
			->page($page, $page_size)
			->order('id desc')
			->select()->toArray();
		$res   = [
			'total' => $total,
			'list'  => $lists,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	/**
	 * 收藏操作
	 *
	 * @return Json
	 * @throws \think\Exception
	 */
	public function collection_action()
	{
		$goods_id = Request::post('goods_id/d');
		$action   = Request::post('action/d');
		if (empty($goods_id)) {
			return $this->callback(ApiConstant::PARAM_ERROR, '参数错误');
		}

		$check = parent::checkUserToken($this->token);
		if ($check !== true) {
			return $this->callback(ApiConstant::NO_LOGIN, $check);
		}
		$user_id = \app\model\User::where('token', $this->token)->value('id');
		$query   = GoodsCollection::where('user_id', $user_id);
		$info    = $query->where('goods_id', $goods_id)->field('id, status')->find();
		if ($info) {
			if ($action == 1 && $info['status'] == 1) {
				return $this->callback(ApiConstant::FAILURE, '已添加收藏');
			} elseif ($action == 2 && $info['status'] == 0) {
				return $this->callback(ApiConstant::FAILURE, '已取消收藏');
			}
			$res = GoodsCollection::update([
				'id'     => $info['id'],
				'status' => $action == 1 ? 1 : 0,
			]);
		} else {
			if ($action == 2) {
				return $this->callback(ApiConstant::FAILURE, '商品未收藏');
			}
			$res = GoodsCollection::create([
				'user_id'  => $user_id,
				'goods_id' => $goods_id,
			]);
		}
		if ($res) {
			return $this->callback(ApiConstant::SUCCESS, '操作成功');
		} else {
			return $this->callback(ApiConstant::FAILURE, '操作失败');
		}
	}

	/**
	 * 批量取消收藏
	 *
	 * @return Json
	 * @throws \think\Exception
	 */
	public function cancel_collection()
	{
		$ids = Request::post('ids/a');
		if (empty($ids)) {
			return $this->callback(ApiConstant::PARAM_ERROR, '参数错误');
		}
		$check = parent::checkUserToken($this->token);
		if ($check !== true) {
			return $this->callback(ApiConstant::NO_LOGIN, $check);
		}
		$res = GoodsCollection::where('id', 'in', $ids)->update([
			'id'     => $ids,
			'status' => 0,
		]);
		if ($res) {
			return $this->callback(ApiConstant::SUCCESS, '操作成功');
		} else {
			return $this->callback(ApiConstant::FAILURE, '操作失败');
		}
	}

	/**
	 * 店铺分类列表
	 *
	 * @return Json
	 */
	public function shop_category()
	{
		$lists = ShopCategory::field('id, name')
			->where('status', 1)
			->order('sort asc, id asc')
			->select();
		return $this->callback(ApiConstant::SUCCESS, 'success', $lists);
	}

	/**
	 * 店铺列表
	 *
	 * @return Json
	 */
	public function shops()
	{
		$page      = Request::get('page') ?: 1;
		$page_size = Request::get('page_size') ?: 5;
		if ($page_size > 5) {
			$page_size = 5;
		}
		$keyword  = Request::get('keyword');
		$category = Request::get('category');
		$user     = \app\model\User::field('id, level, agent_id')->where('token', $this->token)->find();
		$level    = $user['level'] ?? 1;

		$query = Shop::field('id, shop_appid, name, image, flags, sale_num, bug_num, delivery_time');
		if (!empty($category)) {
			$query->where('category_id', $category);
		}
		if (!empty($keyword)) {
			$query->where('name', 'like', "%{$keyword}%");
		}
		$total = $query->count();
		$lists = $query
			->page($page, $page_size)
			->order('sort asc, id asc')
			->select()->toArray();
		if ($lists) {
			$app_ids = array_column($lists, 'shop_appid');
			//获取每个店铺各三个商品
			$goods_query = \app\model\Goods::field('id, shop_appid, title, image, sale_price, share_commission, commission, subsidy_commission')
				->where('shop_appid', 'in', $app_ids)
				->where('status', 1);
			if (!empty($user['agent_id'])) {
				$goods_type = AgentMini::where('agent_id', $user['agent_id'])->value('goods_type');
				//合作商自定义商品
				if ($goods_type == 2) {
					$goods_ids = AgentGoods::where('agent_id', $user['agent_id'])->column('goods_id');
					$goods_query->whereIn('id', $goods_ids);
				}
			}

			$goods_lists = $goods_query
				->withAttr('sale_price', function ($value) {
					return $value > 0 ? number_format($value / 100, 2) : 0;
				})
				->withAttr('share_commission', function ($value, $data) use ($level, $user) {
					//如果用户分销等级是2级，则重新计算佣金
					if ($level == 2 || !empty($user['agent_id'])) {
						$setting = AgentDistribution::getLevelInfo($user['agent_id'], $level, 1);
						$ratio   = $setting['ratio'] / 100;
						$price   = round($data['commission'] * $ratio);
					} else {
						$price = $value;
					}
					$price = $price + $data['subsidy_commission'];
					return $price > 0 ? number_format($price / 100, 2) : 0;
				})
				->order('sort', 'asc')
				->order('id', 'asc')
				->select()
				->toArray();

			// 按店铺分组并截取前三个商品
			$grouped_goods = [];
			foreach ($goods_lists as $good) {
				$shop_appid = $good['shop_appid'];
				if (!isset($grouped_goods[$shop_appid])) {
					$grouped_goods[$shop_appid] = [];
				}
				if (count($grouped_goods[$shop_appid]) < 3) {
					$grouped_goods[$shop_appid][] = $good;
				}
			}
			foreach ($lists as &$list) {
				$list['goods'] = $grouped_goods[$list['shop_appid']] ?? [];
			}
		}
		$res = [
			'total' => $total,
			'list'  => $lists,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	public function free()
	{
		$free_info = DistributionSetting::where('uuid', 'free')->value('value');
		if (empty($free_info)) {
			return $this->callback(ApiConstant::FAILURE, '暂未开启新人0元购活动');
		}
		$free_info = json_decode($free_info, true);
		$end_time  = !empty($free_info['end_date']) ? strtotime($free_info['end_date']) : 0;
		if ($free_info['is_expire'] == 1 && time() > $end_time) {
			return $this->callback(ApiConstant::FAILURE, '新人0元购活动已结束');
		}
		$page      = Request::get('page') ?: 1;
		$page_size = Request::get('page_size') ?: 10;

		$query = GoodsFree::field('id, goods_id');
		$total = $query->count();
		$list  = $query
			->with(['goods'])
			->withAttr('sale_price', function ($value) {
				return $value > 0 ? number_format($value / 100, 2) : 0;
			})
			->page($page, $page_size)
			->select()->toArray();
		$res   = [
			'total' => $total,
			'list'  => $list,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	public function column()
	{
		$column_id = Request::get('column_id');
		$user      = \app\model\User::field('id, level, agent_id')->where('token', $this->token)->find();
		$level     = $user['level'] ?? 1;

		$column = GoodsColumn::where('id', $column_id)
			->withAttr('top_image', function ($value) {
				return $value ? get_file_path($value, 1) : '';
			})
			->withAttr('share_image', function ($value) {
				return $value ? get_file_path($value, 1) : '';
			})
			->find();
		$date   = date('Y-m-d');
		if ($column['start_date'] > $date || $column['end_date'] < $date) {
			return $this->callback(ApiConstant::FAILURE, '不在活动时间内');
		}

		$query = GoodsColumnGoods::field('id, goods_id')->where('column_id', $column_id);
		$list  = $query
			->with(['goods'])
			->withAttr('sale_price', function ($value) {
				return $value > 0 ? number_format($value / 100, 2) : 0;
			})
			->withAttr('share_commission', function ($value, $data) use ($level, $user) {
				//如果用户分销等级是2级，则重新计算佣金
				if ($level == 2 || !empty($user['agent_id'])) {
					$setting = AgentDistribution::getLevelInfo($user['agent_id'], $level, 1);
					$ratio   = $setting['ratio'] / 100;
					$price   = round($data['commission'] * $ratio);
				} else {
					$price = $value;
				}
				$price = $price + $data['subsidy_commission'];
				return $price > 0 ? number_format($price / 100, 2) : 0;
			})
			->order('sort', 'asc')
			->select()->toArray();
		$res   = [
			'column' => $column,
			'list'   => $list,
		];
		return $this->callback(ApiConstant::SUCCESS, 'success', $res);
	}

	/**
	 * 生成商品内嵌商品卡片product_promotion_link
	 *
	 * @return Json
	 */
	public function create_promotion_link()
	{
		$goods_id = Request::param('goods_id');
		if (empty($goods_id)) {
			return $this->callback(ApiConstant::PARAM_ERROR, '参数错误');
		}
		$user = \app\model\User::field('id')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '请先登录');
		}
		$openid = UserOauth::where('user_id', $user['id'])->value('openid');
		$goods  = \app\model\Goods::field('id, product_id, shop_appid, head_supplier_appid')->where('id', $goods_id)->find();
		try {
			$res = CommerceApp::getInstance()->getProductPromotionLink($goods['product_id'], $goods['shop_appid'], $goods['head_supplier_appid'], $openid);
			return $this->callback(ApiConstant::SUCCESS, 'success', ['link' => $res]);
		} catch (Exception $e) {
			\app\model\Goods::where('id', $goods_id)->update(['status' => 0]);
			return $this->callback(ApiConstant::FAILURE, '生成失败');
		}
	}

	/**
	 * 生成分享文案
	 *
	 * @return Json
	 */
	public function create_share_text()
	{
		$goods_id = Request::param('goods_id');
		if (empty($goods_id)) {
			return $this->callback(ApiConstant::PARAM_ERROR, '参数错误');
		}
		$user = \app\model\User::field('id, chat_count')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '请先登录');
		}
		if ($user['chat_count'] < 1) {
			return $this->callback(ApiConstant::FAILURE, '生成失败，生成文案次数已用完');
		}

		$goods    = \app\model\Goods::field('id, title, share_text')->where('id', $goods_id)->find();
		$title    = $goods['title'];
		$ai_model = new DeepSeekService();
		$messages = [
			[
				'role'    => 'user',
				'content' => "商品：$title\n需求：生成一个50个字以内的发圈文案，只需要一个",
			],
		];
		try {
			$res              = $ai_model->createChatCompletion($messages);
			$user->chat_count = $user['chat_count'] - 1;
			$user->save();
			$share_text = $res['content'];
			if (empty($goods['share_text'])) {
				\app\model\Goods::where('id', $goods_id)->update(['share_text' => $share_text]);
			}
			return $this->callback(ApiConstant::SUCCESS, 'success', ['text' => $share_text]);
		} catch (Exception $e) {
			return $this->callback(ApiConstant::FAILURE, '生成失败');
		}
	}

	/**
	 * 生成商品短链接
	 *
	 * @return Json
	 */
	public function create_link()
	{
		$goods_id = Request::param('goods_id');
		if (empty($goods_id)) {
			return $this->callback(ApiConstant::PARAM_ERROR, '参数错误');
		}
		$user = \app\model\User::field('id, sharer_appid')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '请先登录');
		}
		if (empty($user['sharer_appid'])) {
			return $this->callback(ApiConstant::FAILURE, '生成失败，请注册推客');
		}
		$goods = \app\model\Goods::field('id, product_id, shop_appid, head_supplier_appid')->where('id', $goods_id)->find();
		try {
			$res = CommerceApp::getInstance()->getProductPromotionLinkInfo($goods['product_id'], $goods['shop_appid'], $goods['head_supplier_appid'], $user['sharer_appid']);
			return $this->callback(ApiConstant::SUCCESS, 'success', ['link' => $res]);
		} catch (Exception $e) {
			\app\model\Goods::where('id', $goods_id)->update(['status' => 0]);
			return $this->callback(ApiConstant::FAILURE, '生成失败');
		}
	}

	/**
	 * 生成商品二维码
	 *
	 * @return Json
	 */
	public function create_qrcode()
	{
		$goods_id = Request::param('goods_id');
		if (empty($goods_id)) {
			return $this->callback(ApiConstant::PARAM_ERROR, '参数错误');
		}
		$user = \app\model\User::field('id, sharer_appid')->where('token', $this->token)->find();
		if (empty($user)) {
			return $this->callback(ApiConstant::NO_LOGIN, '请先登录');
		}
		if (empty($user['sharer_appid'])) {
			return $this->callback(ApiConstant::FAILURE, '生成失败，请注册推客');
		}
		$goods = \app\model\Goods::field('id, product_id, shop_appid, head_supplier_appid')->where('id', $goods_id)->find();
		try {
			$res = CommerceApp::getInstance()->getProductPromotionQrcodeInfo($goods['product_id'], $goods['shop_appid'], $goods['head_supplier_appid'], $user['sharer_appid']);
			return $this->callback(ApiConstant::SUCCESS, 'success', ['link' => $res]);
		} catch (Exception $e) {
			\app\model\Goods::where('id', $goods_id)->update(['status' => 0]);
			return $this->callback(ApiConstant::FAILURE, '生成失败');
		}
	}

}
